package cn.edu.tju.elm.service;

import cn.edu.tju.elm.model.Cart;
import cn.edu.tju.elm.repository.CartRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * ClassName: CartService
 * Package: cn.edu.tju.elm.service
 * Description:
 *
 * @Author Niu Wenhang
 * @Create 2025/9/17 22:02
 * @Version 1.0
 */
@Service
@Transactional
public class CartService {
    private final CartRepository cartRepository;

    public CartService(CartRepository cartRepository) {
        this.cartRepository = cartRepository;
    }

    public Cart addCartItem(Cart cart) {
        return cartRepository.save(cart);
    }

    public List<Cart> getAllCarts(Long userId, Long businessId) {
        return cartRepository.findAllByCustomerIdAndBusinessId(userId, businessId);
    }

    public List<Cart> getCartsByUserId(Long userId) {
        return cartRepository.findByCustomerIdAndDeletedFalse(userId);
    }

    public Optional<Cart> getCartById(Long id) {
        return cartRepository.findById(id);
    }

    public Cart updateCart(Cart cart) {
        return cartRepository.save(cart);
    }

    public void deleteCart(Long id) {
        cartRepository.deleteById(id);
    }

    public void deleteCartsByUserId(Long userId) {
        cartRepository.deleteByCustomerId(userId);
    }

    public List<Cart> getCartsByUserIdAndBusinessId(Long userId, Long businessId) {
        return cartRepository.findByCustomerIdAndBusinessIdAndDeletedFalse(userId, businessId);
    }

    public List<Cart> getCartsByUserIdAndFoodId(Long userId, Long foodId) {
        return cartRepository.findByCustomerIdAndFoodIdAndDeletedFalse(userId, foodId);
    }

    public BigDecimal calculateTotalPrice(Long userId) {
        List<Cart> carts = cartRepository.findByCustomerIdAndDeletedFalse(userId);
        return carts.stream()
                .map(cart -> cart.getFood().getFoodPrice().multiply(new BigDecimal(cart.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}
